/*
 * @Author: xiaosihan
 * @Date: 2021-05-18 00:14:35
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2021-06-05 20:47:47
 */

import React from "react";
import LineSegments from "../LineSegments/LineSegments";
import Object3DComponent, { Object3DComponentProps } from "../Object3D/Object3DComponent";
import Text2D from "../Text/Text2D";
import THREEPlane from "./THREEPlane";

export interface ClipPlaneProps extends Object3DComponentProps {
    size?: number;
}

interface State { }

export default class ClipPlane extends Object3DComponent<ClipPlaneProps, State> {
    constructor(props: ClipPlaneProps) {
        super(props);
    }

    static defaultProps = {
        clipping: false
    }

    clipPlane = new THREEPlane();

    componentDidMount() {
        const { parent } = this.context;
        parent.addClipPlane(this.clipPlane);
    }

    componentWillUnmount() {
        const { parent } = this.context;
        parent.removeClipPlane(this.clipPlane);
    }

    setObjectParam() {
        let keepRun = super.setObjectParam();

        this.clipPlane.normal.set(0, 0, 1);
        this.clipPlane.constant = 0;
        this.clipPlane.applyMatrix4(this.object3d.matrixWorld);

        return keepRun;
    }

    getPlanPoints() {
        const { size = 5 } = this.props;

        let points: Array<[number, number, number]> = [];

        for (let i = 0; i <= size; i++) {
            points.push([-i / 2, i / 2, 0], [i / 2, i / 2, 0]);
            points.push([-i / 2, i / 2, 0], [-i / 2, -i / 2, 0]);
            points.push([-i / 2, -i / 2, 0], [i / 2, -i / 2, 0]);
            points.push([i / 2, i / 2, 0], [i / 2, -i / 2, 0]);
        }

        points.push([size / 2, size / 2, 0], [-size / 2, -size / 2, 0]);

        points.push([size / 2, -size / 2, 0], [-size / 2, size / 2, 0]);

        return points;
    }

    render() {

        const { dev } = this.context;
        const { size = 5 } = this.props;

        if (!dev) {
            return null;
        };

        return (
            <>
                <LineSegments
                    points={this.getPlanPoints()}
                    color={["#f00"]} // 线条的颜色
                    dashSize={1}// 虚线长度
                    gapSize={0} // 虚线间隔
                    dashOffset={0} // 虚线位移调整
                    dashSpeed={0} // 虚线流动速度
                    clipping={false}
                    duration={500}
                />
                <Text2D
                    clipping={false}
                    scale={{ x: size / 5, y: size / 5, z: 0 }}
                    size={1}
                    text="ClipPlane"
                    textAlign="center_center"
                    color="#f00" // 线条的颜色
                    wireframe={true}
                />
            </>
        );
    }

}